package com.boss.salary.controller;

import com.boss.api.dto.ApiResultDTO;
import com.boss.common.base.BasicinfoBaseController;
import com.boss.common.entity.PageDTO;
import com.boss.common.service.ICommonService;
import com.boss.common.util.PageUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.salary.entity.AgencyInfo;
import com.boss.salary.entity.OperrateLogs;
import com.boss.salary.service.IAgencyExtService;
import com.boss.salary.service.IAgencyInfoService;
import com.boss.salary.service.IOperrateLogsService;
import com.boss.sys.ca.user.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.http.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/agencyInfoController", produces = MediaType.APPLICATION_JSON_VALUE)
public class AgencyInfoController extends BasicinfoBaseController {
    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(AgencyInfoController.class);

    @Autowired
    private IAgencyInfoService iAgencyInfoService;

    @Autowired
    private IAgencyExtService iAgencyExtService;

    @Autowired
    private ICommonService iCommonService;

    @Autowired
    private IOperrateLogsService iOperrateLogsService;


    /**
     * 新增 单位表
     * @param agencyInfo
     * @return
     */
    @PostMapping("/saveAgencyInfo")
    public ApiResultDTO saveAgencyInfo(@RequestHeader("X-Token") String tokenid,
                                       @RequestBody AgencyInfo agencyInfo){

        try {
            UserDTO userDTO = getUser(tokenid);
            agencyInfo.setMofDivCode(userDTO.getProvince());
            iAgencyInfoService.insertAgencyInfo(agencyInfo);
            return ApiResultDTO.success(null, "保存成功");
        } catch (Exception e) {
            logger.error("新增 单位表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "新增 单位表数据发生异常");
        }

    }
    @DeleteMapping("/deleteAgencyInfo/{id}")
    public ApiResultDTO deleteAgencyInfo(@RequestHeader("X-Token") String tokenid,
                                         @PathVariable("id") String id){

        try {
            UserDTO userDTO = getUser(tokenid);
            String mofDivCode=userDTO.getProvince();
            Map<String, Object> queryParam = new HashMap<>(1);
            queryParam.put("id",id);
            queryParam.put("mofDivCode",mofDivCode);
            iAgencyInfoService.deleteAgencyInfo(queryParam);
            return ApiResultDTO.success(null, "删除成功");
        } catch (Exception e) {
            logger.error("删除 单位表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "删除 单位表数据发生异常");
        }
    }

    /**
     * 修改单位数据--需要审核
     * @param agencyInfo
     * @return
     */
    @PostMapping("/updateAgencyInfo")
    public ApiResultDTO updateAgencyInfo(@RequestHeader("X-Token") String tokenid,
                                         @RequestBody AgencyInfo agencyInfo){
        try {
            UserDTO userDTO = getUser(tokenid);
            if (!StringUtils.isEmpty(agencyInfo.getAgencyBankNames())) {
                agencyInfo.setAgencyBankName(agencyInfo.getAgencyBankNames().toString());
            }
            iAgencyInfoService.updateAgencyInfo(agencyInfo);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setOperateName("单位信息编辑--工资单位信息编辑--修改发卡银行");
            operrateLogs.setAgencyId(agencyInfo.getId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            return ApiResultDTO.success(null,"修改成功");
        } catch (Exception e) {
            logger.error("修改 单位表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "修改 单位表数据发生异常");
        }
    }


    /**
     * 修改单位数据-不需要审核
     * @param agencyInfo
     * @return
     */
    @PostMapping("/updateAgencyInfoAudit")
    public ApiResultDTO updateAgencyInfoAudit(@RequestHeader("X-Token") String tokenid,
                                              @RequestBody AgencyInfo agencyInfo){
        try {
            UserDTO userDTO = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setOperateName("单位信息编辑--工资单位信息编辑--修改单位信息");
            operrateLogs.setAgencyId(agencyInfo.getId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            if (!StringUtils.isEmpty(agencyInfo.getAgencyBankNames())) {//将银行集合转换成集合字符串赋值给bankName字段
                agencyInfo.setAgencyBankName(agencyInfo.getAgencyBankNames().toString());
            }
            iAgencyInfoService.updateAgencyInfoIsPaymentAgency(agencyInfo);//修改info表ext表verify表3张表
//
            iAgencyInfoService.updateAgencyInfo(agencyInfo);
            return ApiResultDTO.success(null,"修改成功");
        } catch (Exception e) {
            logger.error("修改 单位表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "修改 单位表数据发生异常");
        }
    }

    @GetMapping("/queryAgencyInfoPage")
    public ApiResultDTO queryAgencyInfoPage(@RequestHeader("X-Token") String tokenid,
                                            @RequestParam(value = "page") String page,
                                            @RequestParam(value = "limit") String limit,
                                            @RequestParam(value = "flag") String flag,
                                            @RequestParam(value = "agencyId") String agencyId){
        try {
            // 获取下级单位id
            UserDTO userDTO = getUser(tokenid);
            List<String> childrenId = iCommonService.getAgencyChildrenId(userDTO, agencyId,tokenid);
//            List<String> childrenIds = iCommonService.getAgencyChildrenIds(userDTO, agencyId);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            Map<String, Object> queryParam = new HashMap<>(1);
            queryParam.put("flag", flag);
            queryParam.put("mofDivCode",userDTO.getProvince());
            PageDTO<AgencyInfo> agencyInfoPageDTO = iAgencyInfoService.queryAgencyInfoPage(paginationDTO, queryParam, childrenId);
            return ApiResultDTO.success(agencyInfoPageDTO,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 查询机构名称及其工资编报送审状态和审核状态
     * @param agencyId
     * @return
     */
    @GetMapping("/queryAgencyNameAndState")
    public ApiResultDTO queryAgencyNameAndState(@RequestHeader("X-Token") String tokenid,
                                                @RequestParam(value = "agencyId") String agencyId){
        try {
            //UserDTO userDTO = getUser(tokenid);
            return ApiResultDTO.success(iAgencyInfoService.getAgencyNameAndState(agencyId));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 根据条件获取单位信息
     * @param id
     * @return
     */
    @GetMapping("/queryAgencyInfo")
    public ApiResultDTO queryAgencyInfo(@RequestHeader("X-Token") String tokenid,
                                        @RequestParam(value = "agencyId", required = false) String id) {
        try {
            UserDTO userDTO = getUser(tokenid);
            List<String> childrenId = iCommonService.getAgencyChildrenId(userDTO, id,tokenid);
            return ApiResultDTO.success(iAgencyInfoService.queryAgencyInfo(childrenId), null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 根据id获取单位信息
     * @param id
     * @return
     */
    @GetMapping("/queryAgencyInfoById")
    public ApiResultDTO queryAgencyInfoById(@RequestHeader("X-Token") String tokenid,
                                            @RequestParam(value = "agencyId") String id) {
        try {
            //UserDTO userDTO = getUser(tokenid);
            Map<String, Object> queryParam = new HashMap<>(1);
            queryParam.put("id", id);
            return ApiResultDTO.success(iAgencyInfoService.queryAgencyInfoById(queryParam), null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }

    /**
     * 送审
     * @param agencyInfoList
     * @return
     */
    @PostMapping("/submitVerify")
    public ApiResultDTO submitVerify(@RequestHeader("X-Token") String tokenid,
                                     @RequestBody List<AgencyInfo> agencyInfoList) {
        try {
            UserDTO userDTO = getUser(tokenid);
            iAgencyExtService.submitVerify(agencyInfoList);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setOperateName("单位信息编辑--送审");
            ArrayList<String> agencyId = new ArrayList<>();
            for (AgencyInfo agencyInfo : agencyInfoList) {
                agencyId.add(agencyInfo.getId());
            }
            String agencyIds= org.apache.commons.lang.StringUtils.join(agencyId,",");
            operrateLogs.setAgencyId(agencyIds);
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            return ApiResultDTO.success(null,"送审成功");
        } catch (Exception e) {
            logger.error("送审发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE,"送审发生异常");
        }
    }

    /**
     * 撤销送审
     * @param agencyInfoList
     * @return
     */
    @PostMapping("/revokeVerify")
    public ApiResultDTO revokeVerify(@RequestHeader("X-Token") String tokenid,
                                     @RequestBody List<AgencyInfo> agencyInfoList) {
        try {
            UserDTO userDTO = getUser(tokenid);
            iAgencyExtService.revokeVerify(agencyInfoList);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setOperateName("单位信息编辑--撤销送审");
            ArrayList<String> agencyId = new ArrayList<>();
            for (AgencyInfo agencyInfo : agencyInfoList) {
                agencyId.add(agencyInfo.getId());
            }
            String agencyIds= org.apache.commons.lang.StringUtils.join(agencyId,",");
            operrateLogs.setAgencyId(agencyIds);
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            return ApiResultDTO.success(null,"撤销送审成功");
        } catch (Exception e) {
            logger.error("撤销送审发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销送审发生异常");
        }
    }

    /**
     * 获取所有单位信息
     * @return
     */
    @GetMapping("/getAllAgency")
    public ApiResultDTO getAllAgency(@RequestHeader("X-Token") String tokenid) {
        try {
            UserDTO userDTO = getUser(tokenid);
            return ApiResultDTO.success(iAgencyInfoService.getAllAgency(userDTO), null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取异常");
        }
    }

    /**
     * 查询单位拓展信息
     * @param tokenid
     * @param agencyId
     * @return
     */
    @GetMapping("/getAgencyInfo")
    public ApiResultDTO getAgencyInfo(@RequestHeader("X-Token") String tokenid,
                                      @RequestParam("agencyId") String agencyId) {
        try {
            //UserDTO userDTO = getUser(tokenid);
            return ApiResultDTO.success(iCommonService.getAgencyInfo(tokenid, agencyId));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询单位拓展信息异常");
        }
    }

    /**
     * 根据id查单位名称
     * @param agencyId
     * @return
     */
    @GetMapping("/getAgencyNameById")
    public ApiResultDTO getAgencyNameById(@RequestHeader("X-Token") String tokenid,
                                          @RequestParam("agencyId") String agencyId){
        try {
            //UserDTO userDTO = getUser(tokenid);
            return ApiResultDTO.success(iAgencyInfoService.getNameById(agencyId), null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取异常");
        }
    }

    @GetMapping("/getIsLeafIds")
    public ApiResultDTO ids(){
        try {
            return ApiResultDTO.success(iAgencyInfoService.getIds());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取异常");
        }
    }

    @GetMapping("/getAgencyIds")
    public ApiResultDTO getAgencyIds(@RequestBody List<String> agencyCodes){
        try {
            return ApiResultDTO.success(iAgencyInfoService.getAgencyIds(agencyCodes));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取异常");
        }
    }

    /**
     * 根据id获取单位信息
     * @param id
     * @return
     */
    @GetMapping("/agencyPerson")
    public ApiResultDTO agencyPerson( @RequestParam(value = "agencyId") String id) {
        try {
            return ApiResultDTO.success(iAgencyInfoService.agencyPerson(id), null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }
}